package com.rpp;

import com.rpp.handler.UserServiceHandler;
import com.rpp.request.RpcRequest;
import com.rpp.serialize.JSONSerializer;
import com.rpp.utils.RpcDecoder;
import com.rpp.utils.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/4 11:25 下午
 */
@SpringBootApplication
public class ServerBootStrap {

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(ServerBootStrap.class, args);

        //启动服务器
        startServer("127.0.0.1", 8999);
    }

    /**
     * 启动服务器
     *
     * @param ip
     * @param port
     * @throws InterruptedException
     */
    public static void startServer(String ip, int port) throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //设置编码器
                        pipeline.addLast(new RpcEncoder(String.class, new JSONSerializer()));
                        //设置解码器
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把自定义ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        System.out.println("服务端启动成功。。。开始绑定端口");
        //4.绑定端口
        serverBootstrap.bind(8999).sync();
    }
}
